package com.wwdx.controller.rest;

import com.google.common.collect.Lists;
import com.wwdx.controller.base.BaseController;
import com.wwdx.model.ReVersionModel;
import com.wwdx.model.WwdxBookModel;
import com.wwdx.model.dto.BaseActivityDTO;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import com.wwdx.utils.QrCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.http.URIUtil;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author liguoliang
 */
@RestController
@RequestMapping("other")
@Api(tags = "其它接口")
public class RestOtherController extends BaseController{

    /**
     * 蜜读获取微信H5签名
     */
    @RequestMapping("/jssgin")
    @ApiOperation(value = "获取微信H5签名信息",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url",value = "需要签名的URL",required = true)
    })
    public ResultBean jssgin(String url){
        return this.execute(url,miDuWxService);
    }

    private ResultBean execute(String url, WxMpService service){
        try {
            return renderSuccess(service.createJsapiSignature(url));
        }catch (WxErrorException e){
            logger.error(e.getMessage());
            return renderError(e.getMessage());
        }
    }

    /**
     * 测试公众号
     */
    @RequestMapping("/jssgin2")
    @ApiIgnore
    public ResultBean jssgin2(String url){
        return this.execute(url,testWxService);
    }

    /**
     * 获取公众号带LOGO二维码
     */
    @RequestMapping("/qrcode")
    @ApiOperation(value = "获取二维码图片",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url",value = "二维码跳转地址",required = true)
    })
    public void qrcode(String url, HttpServletRequest request, HttpServletResponse response)throws Exception {
        String realPath = request.getSession().getServletContext().getRealPath("/");
        String imgPath = realPath+"public/img/midu_logo.png";
        String orginal = wechatUrl+"auth.html?url="+ URIUtil.encodeURIComponent(url);
        //生成产短链接
        String shortUrl = miDuWxService.shortUrl(orginal);
        QrCodeUtil.encode(shortUrl, imgPath,response.getOutputStream(), true);
    }

    /**
     * springMvc 上传图片
     * 1.enctype属性的属性值设为multipart/form-data。
     * 2.input的type属性的属性值设为file。
     * 后台就可以使用multipartResolver获取到前台上传的文件
     */
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void upload2(@RequestParam(value = "file",required = false) MultipartFile file,String unionid) {
        try {
            if(!file.isEmpty()){
                String realPath = "/data/wwdx/static/pullxin/";
                String fileName = unionid + FilenameUtils.getExtension(file.getOriginalFilename());
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName));
            }
        }catch (IOException e){
            logger.error("上传失败,{}",e.getMessage());
        }
    }

    /**
      赠一得一书籍列表
     * @param unionid 用户业务ID
     */
    @RequestMapping("/giveonewindow")
    @ApiOperation(value = "赠一得一书籍列表",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "unionid",value = "用户业务ID")
    })
    public ResultBean giveonewindow(String unionid) {
        String phaseListKey = ConstantHolder.GIVEONE_PHASE_LIST;
        List<Object> range = listOperations.range(phaseListKey, 0, 0);
        if (!CollectionUtils.isEmpty(range)) {
            String phaseKey = (String) range.get(0);
            BaseActivityDTO.GiveOneDTO giveOneDTO = (BaseActivityDTO.GiveOneDTO) valueOperations.get(phaseKey);
            String bookListKey = String.format(ConstantHolder.GIVEONE_BOOK_LIST, giveOneDTO.getPhase());
            range = listOperations.range(bookListKey, 0, -1);
            List<WwdxBookModel> wwdxBookModels = Lists.newArrayListWithExpectedSize(range.size());
            for (Object bookid : range) {
                wwdxBookModels.add(wwdxBookService.getByBookId(Long.valueOf(bookid.toString())));
            }
            giveOneDTO.setBook_list(productService.bookList(wwdxBookModels, unionid));
            return renderSuccess(giveOneDTO);
        }
        return renderSuccess();
    }


    /**
     * 随机6本书
     */
    @RequestMapping("/random/book")
    @ApiIgnore
    public ResultBean randombook(){
        WwdxBookModel wwdxBookModel = WwdxBookModel.builder().status(0).type(0).random(true).build();
        return renderSuccess(wwdxBookService.selectModelList(wwdxBookModel,1,6));
    }

    /**
     * ios 获取更新版本
     */
    @RequestMapping("/version/get")
    @ApiIgnore
    public ResultBean get(Long channelid, String version) {
        ReVersionModel reVersionModel = reVersionService.getVersionModel(channelid);
        if (reVersionModel != null){
            String versioncode = reVersionModel.getVersioncode();
            boolean equals = StringUtils.equals(versioncode, version);
            if (!equals) {
                String[] strArray;
                int length = 2;
                strArray = versioncode.split("\\.");
                if (strArray.length > length) {
                    versioncode = strArray[0] + "." + strArray[1] + strArray[2];
                }
                String[] strArrayversion;// 客户端字符串数组
                strArrayversion = version.split("\\.");
                if (strArrayversion.length > length) {
                    version = strArrayversion[0] + "." + strArrayversion[1] + strArrayversion[2];
                }
                if (Double.parseDouble(versioncode) > Double.parseDouble(version)) {
                    return renderSuccess(reVersionModel);
                }
            }
        }
        return renderError("暂无更新内容");
    }
}